import {defineStore} from "pinia";
import {getVerification} from "@/api/request";

export const useMain = defineStore("useStore", {
    /**
     * 存储全局状态
     * 1.必须是箭头函数: 为了在服务器端渲染的时候避免交叉请求导致数据状态污染
     * 和 TS 类型推导
     */
    state: () => {
        return {
            changeModule: 0,
            themeChange: "",
            token: "",
            isShowTheme: false, // 是否显示主题切换
            isLogin: false,
        };
    },
    /**
     * 用来封装计算属性 有缓存功能  类似于computed
     */
    getters: {
        getChangeModule: (state) => {
            return state.changeModule;
        },
        getChangeTheme: (state) => {
            return state.themeChange;
        },
        getShowTheme: (state) => {
            return state.isShowTheme;
        },
        getIsLogin: (state) => {
            return state.isLogin;
        },
    },
    /**
     * 编辑业务逻辑  类似于methods
     */
    actions: {
        // token校验
        setToken(token: string) {
            if (token) {
                getVerification(token)
                    .then(() => {
                        this.isLogin = true;
                        // 在这里可以将 token 存储到 localStorage 中
                        localStorage.setItem("token", token);
                    })
                    .catch(() => {
                        // 删除token
                        localStorage.removeItem("token");
                    });
            }
        },
        setChangeTheme(state: string) {
            this.themeChange = state;
        },
        setShowTheme(state: boolean) {
            this.isShowTheme = state;
        },
    },
});
